package com.distribute.framework.core.util;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 数组工具类
 * Created vincent on 2019/1/2
 */
public class ArrayTools {

    private static <T> T[] clone(T[] array) {
        return array == null ? null : (T[]) array.clone();
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] addAll(T[] array1, T... array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        } else {
            Class<?> cls = array1.getClass().getComponentType();
            T[] joinedArray = (T[]) Array.newInstance(cls, array1.length + array2.length);
            System.arraycopy(array1, 0, joinedArray, 0, array1.length);

            try {
                System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
                return joinedArray;
            } catch (ArrayStoreException e) {
                Class<?> type2 = array2.getClass().getComponentType();
                if (!cls.isAssignableFrom(type2)) {
                    throw new RuntimeException("Cannot store " + type2.getName() + " in an array of " + cls.getName(), e);
                } else {
                    throw e;
                }
            }
        }
    }

    public static <T> Set<T> delRepeat(T[] array){
        List<T> list = Arrays.asList(array);
        return new HashSet<>(list);
    }

    public static <T> void removeArg(List<T> list, T arg){
        int i = 0;
        for (T t : list){
            if (t.equals(arg)){
                i += 1;
            }
        }
        for(int j = 0; j < i; j++){
            list.remove(arg);
        }
    }

}